package cn.app.wx.controller;

import cn.app.wx.dao.UserDao;
import cn.app.wx.model.User;
import cn.jfast.framework.jdbc.annotation.Transaction;
import cn.jfast.framework.web.api.annotation.Api;
import cn.jfast.framework.web.api.annotation.Get;
import cn.jfast.framework.web.api.annotation.Post;
import cn.jfast.framework.web.view.Route;
import cn.jfast.framework.web.view.viewtype.Json;
import cn.jfast.framework.web.view.viewtype.Jsp;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

@Api("/jsp")
public class LoginController {

    @Resource
    UserDao userDao;

    @Transaction
    @Post("login")
    public Json login(String email,String password,HttpServletRequest request) throws SQLException, ClassNotFoundException {
        User user = userDao.selectAllFromUserByEmailPassword(email,password);
        if(null != user) {
            request.getSession().setAttribute("user", user);
            return new Json("{login:true}");
        } else {
            return new Json("{login:false}");
        }
    }

    @Post("home")
    @Get("home")
    public Jsp home(HttpServletRequest request){
        if(null != request.getSession().getAttribute("user"))
            return new Jsp("jsp/home", Route.REDIRECT);
        else
            return null;
    }

    @Post("logout")
    public Json logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return new Json("{logout:true}");
    }

}
